package com.wing.cabinet.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.CheckedResult;
import com.wing.cabinet.model.request.CheckedResultForm;
import com.wing.cabinet.model.response.CheckedResultVO;
import com.wing.cabinet.model.response.CheckedScrapVO;
import com.wing.cabinet.model.response.TemporaryStorageExportVO;
import com.wing.cabinet.service.CheckedResultService;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.DepartmentVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-盘验结果表管理", tags = "#/cabinet/checkedRecycleResult")
@RestController("checkedRecycleResultController")
@RequestMapping("cabinet/admin/checkedRecycleResult")
@RequiredArgsConstructor
public class CheckedRecycleResultController {

    private final CheckedResultService checkedResultService;
    @Autowired
    private UserClient userClient;

    @ApiOperation(value = "查询所有盘验结果表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CheckedResultVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,String code
            ,String cabCode
            ,String skuCode
            ,String startTime
            ,String endTime
            ,Long creatorId
            ,Long departmentId
    ){

        Page<CheckedResult> pg = new Page<>(page, limit);
        Map queryParam=new HashMap();
        queryParam.put("sort",StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("code",code);
        queryParam.put("cabCode",cabCode);
        queryParam.put("skuCode",skuCode);
        queryParam.put("startCreateTime",startTime);
        queryParam.put("endCreateTime",endTime);
        queryParam.put("businessType",CheckedResult.BusinessType.recycle.getValue());
        //搜索
        queryParam.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        if (creatorId!=null){
            queryParam.put("creatorId",creatorId);
        }
        if (departmentId!=null&&creatorId==null){
            queryParam.put("departmentId",departmentId);
        }
        IPage<CheckedResultVO> list = checkedResultService.pageList4app(pg,queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加盘验结果表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CheckedResultForm.Add.class) CheckedResultForm checkedResultForm) {
        if (checkedResultService.add(checkedResultForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改盘验结果表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CheckedResultForm.Update.class) CheckedResultForm checkedResultForm) {
        CheckedResult checkedResult = checkedResultService.getById(checkedResultForm.getId());
        if(checkedResult == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CheckedResult.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(checkedResultForm, checkedResult, copyOptions);
        if (checkedResultService.updateById(checkedResult)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除盘验结果表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "checkedResultId", value = "盘验结果表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long checkedResultId) {
        if (checkedResultService.removeById(checkedResultId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "导出数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime){
        List<CheckedScrapVO> list = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
        paramsMap.put("businessType",CheckedResult.BusinessType.recycle.getValue());

        list = checkedResultService.getCheckedScrapVoExportList(paramsMap);
        for(CheckedScrapVO item : list){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            item.setCostCenter(jsonResult.getData().getCostCenter());
        }
        //导出
        ExcelUtils.export(response,"已盘报废记录",list, CheckedScrapVO.class);
    }
}
